package zyutils

import (
	"log"
	"math/rand"
	"strconv"
	"time"
	"unsafe"

	uuid "github.com/satori/go.uuid"
)

func StrToInt(from string) (to int) {
	to, err := strconv.Atoi(from)
	if err != nil {
		log.Panic(err)
	}
	return to
}

func StrToIntOrDef(from string, def int) (to int) {
	to, err := strconv.Atoi(from)
	if err != nil {
		return def
	}
	return to
}

func StrToFloat64(from string) (to float64) {
	to, err := strconv.ParseFloat(from, 64)
	if err != nil {
		log.Panic(err)
	}
	return to
}

func StrToFloat64OrDef(from string, def float64) (to float64) {
	to, err := strconv.ParseFloat(from, 64)
	if err != nil {
		return def
	}
	return to
}

func GenerateID(n int) string {
	const (
		letterIdxBits = 6                    // 6 bits to represent a letter index
		letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
		letterIdxMax  = 63 / letterIdxBits   // # of letter indices fitting in 63 bits
	)
	src := rand.NewSource(time.Now().UnixNano())
	letters := []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
	b := make([]byte, n)
	// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
	for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
		if remain == 0 {
			cache, remain = src.Int63(), letterIdxMax
		}
		if idx := int(cache & letterIdxMask); idx < len(letters) {
			b[i] = letters[idx]
			i--
		}
		cache >>= letterIdxBits
		remain--
	}
	return *(*string)(unsafe.Pointer(&b))

}

func GenerateUUID() string {
	return uuid.NewV4().String()
}
